
/* model */
import Column from '@model/types/Column';
import { TABLE_MAX_CHECKED_COUNT } from '@src/model/const/Number';
/* enum */
import ElementTableSortOrderEnum from '@model/enum/ElementTableSortOrderEnum';
import SortModeEnum from '@model/enum/SortModeEnum';
/* util */
import { simplifyTableColumnsProperty, saveDataToStorage } from '@src/modules/projectManage/projectManageList/util';
import Platform from '@src/util/platform';
import { t } from '@src/locales';
import _ from 'lodash';
/* vue */
import { ref, computed, nextTick } from 'vue';

export function useTable() {
  // 表格组件ref
  const tableComponentRef = ref();
  // 已选择项
  let multipleSelection = ref([] as any);
  // 已选项ids
  const selectedIds = computed(() => {
    return multipleSelection.value.map((item: any) => item.id);
  })

  // 计算已选择
  const selectionCompute = (selection: any[], data: any[]) => {
    let tv = []
    
    tv = multipleSelection.value.filter((ms: any) => data?.every((item: any) => item.id !== ms.id));
    tv = _.uniqWith([...tv, ...selection], _.isEqual);
    
    return tv
  }

  // 表格选择操作
  const handleSelection = (selection: any[], data: any[]) => {
    // 计算已选择的数据
    const tv = selectionCompute(selection, data);

    // 计算当前页已选择的数据
    const originalSelected = multipleSelection.value.filter((ms: any) => data.some((cs: any) => cs.id === ms.id));
    // 计算当前页未选择的数据（用于超出选择最大限制时取消勾选）
    const unSelected = data.filter(item => originalSelected.every((oc: any) => oc.id !== item.id)) || [];

    // 判断是否超出最大选择限制
    if (tv.length > TABLE_MAX_CHECKED_COUNT) {
      unSelected.forEach(row => {
        tableComponentRef.value.toggleRowSelection(row, false);
      });

      return Platform.alert(t('common.base.tip.choiceLimit', {limit: TABLE_MAX_CHECKED_COUNT}));
    }

    multipleSelection.value = tv;

    tableComponentRef.value?.doLayout();
  }

  // 清除表格选择项
  const clearSelection = () => {
    multipleSelection.value = [];
    tableComponentRef.value?.clearSelection();
    tableComponentRef.value?.doLayout();
  }

  // 把选中的匹配出来
  const matchSelected = (data: any[]) => {
    if (!multipleSelection.value.length) return;

    // 计算当前页已选择的数据
    const selected = data.filter(ms => multipleSelection.value.some((cs: any) => cs.id === ms.id)) || [];

    nextTick(() => {
      selected.forEach(row => {
        tableComponentRef.value.toggleRowSelection(row, true);
      });
    });
  }

  // 处理表格拖动
  const disposeHeaderDragendColumns = (newWidth: number, tableColumn: any = {}, originColumns: Column[], storageKey: string) => {
    let field: string = tableColumn.property || '';
    let column: Column | null = null;
    
    for (let i = 0; i < originColumns.length; i++) {
      column = originColumns[i];
      if (column.field === field) {
        column.width = newWidth;
      }
    }

    // 精简列数据
    const columns = simplifyTableColumnsProperty(originColumns);

    // 保存到缓存
    saveDataToStorage(storageKey, columns);
  }

  // 处理表格排序
  const disposeTableSortChanged = (option: { prop?: any, order?: any } = {}) => {
    const { prop, order } = option;

    // 排序条件
    let orderDetail: any = {};

    if (order) {
      orderDetail = {
        column: prop,
        asc: order === ElementTableSortOrderEnum.ASC,
      }
    }

    return orderDetail;
  }
  
  return {
    tableComponentRef,
    multipleSelection,
    selectedIds,

    handleSelection,
    clearSelection,
    matchSelected,
    disposeHeaderDragendColumns,
    disposeTableSortChanged,
  }
}
